package com.yuyang.wifi.receiver;

import android.Manifest;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.yuyang.wifi.MyApplication;
import com.yuyang.wifi.R;
import com.yuyang.wifi.activitys.login.WeChatLoginActivity;
import com.yuyang.wifi.activitys.mine.LockScreenActivity;
import com.yuyang.wifi.base.AppManager;
import com.yuyang.wifi.base.BaseResult;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.jobservice.AppService;
import com.yuyang.wifi.jobservice.KeepAliveJobService;
import com.yuyang.wifi.model.CheckAdResult;
import com.yuyang.wifi.model.CheckModel;
import com.yuyang.wifi.model.TaskDtlModel;
import com.yuyang.wifi.model.TaskDtlResult;
import com.yuyang.wifi.service.LiveWallpaperService;
import com.yuyang.wifi.utils.ActivityAllManager;
import com.yuyang.wifi.utils.GetIPAdsUtil;
import com.yuyang.wifi.utils.GetMacAdsUtil;
import com.yuyang.wifi.utils.Parser;
import com.yuyang.wifi.utils.PreferencesProviderUtils;
import com.yuyang.wifi.utils.RxUtil;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.utils.network.BaseDataSubscriber;
import com.yuyang.wifi.utils.network.HttpErrorHandler;
import com.yuyang.wifi.utils.network.HttpManager;
import com.yuyang.wifi.utils.network.RxDataInstance;
import com.yuyang.wifi.views.MittUtils;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 全局广播接收器。用于接收关闭屏幕的广播、来电广播等。
 *
 * @author zhangqie
 */
public class AppReceiver extends BroadcastReceiver {

    private Context mContext;
    private int mType = 1;
    private PowerManager.WakeLock wakeLock = null;
    private String mOaid;

    static {
        System.loadLibrary("cql-ref");
    }

    @Override
    public void onReceive(final Context context, Intent intent) {

        String intentAction = intent.getAction();
        int tag = Log.e("TAG", "广播动作===:" + intentAction);
//        1:亮屏  2：插电|拔电 3：WIFI连接|断开  4：安装|卸载
        mContext = context;
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, AppService.class.getName());
        }
        wakeLock.acquire();
        Log.e("TAG", "MyApplication==手机休眠调起" + intentAction);
        switch (intentAction) {
            case Intent.ACTION_USER_PRESENT:

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    mContext.startForegroundService(new Intent(mContext, AppService.class));
                } else {
                    mContext.startService(new Intent(mContext, AppService.class));
                }

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    KeepAliveJobService.startJob(mContext);
                }

                doNext(1, 1);
                Log.e("msg==", "onReceive: ===" + intentAction);
                Log.e("TAG", "onReceive: ===亮屏 ");
                break;
            case Intent.ACTION_POWER_CONNECTED:
                doNext(2, 2);
            case Intent.ACTION_POWER_DISCONNECTED:
                //插上/断开外部电源时发出的广播
                //Toast.makeText(context, "插上/断开外部电源时发出的广播~" + mType, Toast.LENGTH_LONG).show();
                Log.e("TAG", "onReceive: ===插上/断开外部电源时发出的广播 ");
                doNext(2, 3);
                break;
            case Intent.ACTION_PACKAGE_ADDED:
                doNext(4, 4);
                break;
            case Intent.ACTION_PACKAGE_REMOVED:
                Log.e("TAG", "onReceive: ===应用被安装/卸载了 ");
                //Toast.makeText(context, "应用被安装/卸载了~" + mType, Toast.LENGTH_LONG).show();
                //触发一个下载并且完成安装时发出的广播，比如在电子市场里下载应用？
                doNext(4, 5);
                break;
            case "android.net.wifi.supplicant.CONNECTION_CHANGE"://加速状态
                Log.e("TAG", "onReceive: android.net.wifi.supplicant.CONNECTION_CHANGE ");
                //Toast.makeText(context, "wifi没连接上~" + mType, Toast.LENGTH_LONG).show();
                doNext(3, 6);
                break;
            case Intent.ACTION_CLOSE_SYSTEM_DIALOGS:
                ActivityAllManager.getInstance().finishAllActivity();
                String SYSTEM_REASON = "reason";
                String SYSTEM_HOME_KEY = "homekey";
                String SYSTEM_HOME_KEY_LONG = "recentapps";
                String reason = intent.getStringExtra(SYSTEM_REASON);
                Log.e("TAG", "MyApplication==SYSTEM行为===" + reason);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG) || TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    //表示按了home键,程序到了后台
                    doNext(5, 1);
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            doNext(5, 1);
//                        }
//                    }, 1000);
                }
                break;
            default:
                Parser.killBackgroundProcess(context);
                break;
        }
    }

    private void doNext(int type, int boardType) {
        if (Parser.sPhoneCallState == TelephonyManager.CALL_STATE_IDLE) { // 手机状态为未来电的空闲状态
            //整体判断当前应用是否在前台,确定是否播放外部广告
            Log.e("TAG", "appReceiver==" + "广播触发类型==" + type);
            SpUtil.saveOrUpdate(AppConstant.KEY_OUTSIDE_AD_TYPE, type + "");
            SpUtil.saveOrUpdate(AppConstant.KEY_BOARD_TYPE, boardType + "");
            if (type == 5) {
                getAdTypeInfo();
            }
            //非壁纸服务
            if (mType == 1) {
                boolean pagerServiceRunning = isPagerServiceRunning();
                if (!pagerServiceRunning) {
                    //ActivityAllManager.getInstance().finishAllActivity();
                    if (isAppServiceRunning()) {
                        // Toast.makeText(mContext, "我是广播,isAppServiceRunning正在运行~", Toast.LENGTH_LONG).show();
                        int time = 3;
                        if (type == 2) {
                            time = 0;
                        }
                        Log.e("TAG", "服务===3333" + "");
                        AppService appService = new AppService();
                        //AppService appService = AppService.getInstance();
                        appService.lunchAC(mContext, time, type + "", boardType + "");
                    }
                }
            } else {
                //Toast.makeText(mContext, "我是广播,亮屏收到了~" + mType, Toast.LENGTH_LONG).show();
                int time = 3;
                if (type == 2) {
                    time = 0;
                }
                Log.e("TAG", "服务===22222" + "");
                LiveWallpaperService liveWallpaperService = new LiveWallpaperService();
                liveWallpaperService.lunchAC(time, type + "", boardType + "");
            }
        }
    }

    public void setType(int type) {
        mType = type;
    }

    private boolean isPagerServiceRunning() {
        ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.yuyang.wifi.service.LiveWallpaperService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    private boolean isAppServiceRunning() {
        ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.yuyang.wifi.jobservice.AppService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }


    private void getAdTypeInfo() {
        mOaid = SpUtil.find(AppConstant.KEY_OAID);
        if (TextUtils.isEmpty(mOaid)) {
            new MittUtils().getDeviceIds(mContext, new MittUtils.AppIdsUpdater() {
                @Override
                public void OnIdsAvailed(boolean isSupport, String oaid) {
                    SpUtil.saveOrUpdate(AppConstant.KEY_OAID, oaid);
                    mOaid = oaid;
                    Log.e("参数", "oaid:=== " + oaid);
                }
            });
        }

        String mac = GetMacAdsUtil.getMac(mContext);
        String ipAddress = GetIPAdsUtil.getIPAddress(mContext);
        String androidid = getAndroidId(mContext);
        String imei = getDeviceIds(mContext);
        RxDataInstance.getInstance().initMap(mContext)
                .put("imei", imei)
                .put("oaid", mOaid)
                .put("idfa", "")
                .put("androidid", androidid)
                .put("mac", mac)
                .put("ip", ipAddress)
                .put("bigtype", "5");
        HttpManager.getInstance().getApi().check(RxDataInstance.getInstance().getParamMap())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseDataSubscriber<CheckAdResult>(new HttpErrorHandler() {
                    @Override
                    public void onHttpError(BaseResult result) {
                        // ToastUtils.showShortToast(LockScreenActivity.this, result.getErrorMessage());
                    }

                    @Override
                    public void onHttpException(Throwable e) {
                        // dismissLoadingDialog();
                    }
                }) {
                    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                    @Override
                    public void onDataNext(CheckAdResult result) {
                        int resultCode = result.getResultCode();
                        if (0 == resultCode) {
                            String data = result.getData();
                            if (!TextUtils.isEmpty(data)) {
                                PreferencesProviderUtils.putString(mContext, "home_check", AppConstant.KEY_HOME_CHECK, "continue");
                            } else {
                                PreferencesProviderUtils.putString(mContext, "home_check", AppConstant.KEY_HOME_CHECK, "return");
                            }
                        } else {
                            // ToastUtils.showShortToast(LockScreenActivity.this, result.getErrorMessage());
                        }
                    }
                });
    }

    private static String getAndroidId(Context context) {
        String deviceID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        if (!TextUtils.isEmpty(deviceID)) {
            return deviceID;
        }
        return deviceID;
    }

    //获取设备ID
    public static String getDeviceIds(Context context) {

        try {
            TelephonyManager telephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyMgr != null) {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    return "";
                }
                String deviceId = telephonyMgr.getDeviceId();
                //Log.e("channel", "onViewClicked:" + deviceId);
                return deviceId;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }


}